package com.file.parser;


import com.file.bo.AppTaxIncome;
import com.file.bo.AppTaxIncomeTran;
import com.file.bo.ResponseData;
import com.file.constant.ErrorCode;
import com.file.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Slf4j

public class AppTaxIncomeHtmlParser {

    public ResponseData<String> parseAppTaxIncomeHtmlToJson(String daId, String filePath) {
        log.info("parseAppTaxIncomeHtmlToJson started, daId:{}", daId);
        String json;

        try {
            AppTaxIncome appTaxIncome = parseAppTaxIncomeHtml(filePath);
            json = JsonUtils.convertObjectToJson(appTaxIncome);
        } catch (Exception e) {
            log.error("OnError|{}||{}|{}|{}|{}", ErrorCode.FILE_PARSE_EXCEPTION.getCode(), daId, "", "", "parseAppTaxIncomeHtmlToJson failed", e);
            return new ResponseData<>(null, ErrorCode.FILE_PARSE_EXCEPTION.getCode(),
                    ErrorCode.FILE_PARSE_EXCEPTION.getMsg());
        }

        log.info("parseAppTaxIncomeHtmlToJson completed, daId:{}, json:{}", daId, json);
        return new ResponseData<>(json, ErrorCode.SUCCESS.getCode(), ErrorCode.SUCCESS.getMsg());
    }

    public AppTaxIncome parseAppTaxIncomeHtml(String filePath) throws IOException {
        File input = new File(filePath);
        AppTaxIncome appTaxIncome = new AppTaxIncome();
        List<AppTaxIncomeTran> appTaxIncomeTrans = new ArrayList<>();

        Document doc = Jsoup.parse(input, "UTF-8");

        String totalIncome = doc.select(".srhj > span").get(1).text();
        appTaxIncome.setTotalIncome(StringUtils.equals(totalIncome, "--") ? "0.00元" : totalIncome);
        String totalDeclaredTax = doc.select(".ysbsehj > span").get(1).text();
        appTaxIncome.setTotalDeclaredTax(StringUtils.equals(totalDeclaredTax, "--") ? "0.00元" : totalDeclaredTax);

        if (hasTaxIncomeData(filePath)) {
            Elements elements = doc.select(".c-tax-record-item-left");
            for (int i = 0; i< elements.size(); i++) {
                Element element = elements.get(i);
                AppTaxIncomeTran appTaxIncomeTran = new AppTaxIncomeTran();
                String temp = element.select(".c-tax-record-item-title").text();
                String taxPeriod = element.select(".c-tax-record-item-title > span").text();
                String incomeItem = temp.substring(0, temp.indexOf(taxPeriod)).trim();
                String incomeItemSubCategory = null;
                String withholdingAgent = null;
                String income = null;
                String declaredTax = null;
                if (element.select(".c-tax-record-item-date > span").size() > 7) {
                    incomeItemSubCategory = element.select(".c-tax-record-item-date > span").get(1).text();
                    withholdingAgent = element.select(".c-tax-record-item-date > span").get(3).text();
                    income = element.select(".c-tax-record-item-date > span").get(5).text();
                    declaredTax = element.select(".c-tax-record-item-date > span").get(7).text();
                } else if (element.select(".c-tax-record-item-date > span").size() > 5) {//已知新用例适配
                    if (!element.select(".c-tax-record-item-date > span").text().contains("扣缴义务人")) {
                        incomeItemSubCategory = element.select(".c-tax-record-item-date > span").get(1).text();
                        withholdingAgent = "";
                        income = element.select(".c-tax-record-item-date > span").get(3).text();
                        declaredTax = element.select(".c-tax-record-item-date > span").get(5).text();
                    }
                }
                appTaxIncomeTran.setIncomeItem(incomeItem);
                appTaxIncomeTran.setTaxPeriod(taxPeriod);
                appTaxIncomeTran.setIncomeItemSubCategory(incomeItemSubCategory);
                appTaxIncomeTran.setWithholdingAgent(withholdingAgent);
                appTaxIncomeTran.setIncome(StringUtils.equals(income, "--") ? "0.00元" : income);
                appTaxIncomeTran.setDeclaredTax(StringUtils.equals(declaredTax, "--") ? "0.00元" : declaredTax);
                appTaxIncomeTrans.add(appTaxIncomeTran);
            }
            appTaxIncome.setAppTaxIncomeTrans(appTaxIncomeTrans);
        }

        return appTaxIncome;
    }

    public boolean hasTaxIncomeData(String filePath) {
        boolean hasTaxIncomeData = true;

        try {
            File input = new File(filePath);
            Document doc = Jsoup.parse(input, "UTF-8");
            Elements taxIncomeElements = doc.select(".c-tax-record-item-left");
            if (taxIncomeElements.size() == 0) {
                hasTaxIncomeData = false;
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return hasTaxIncomeData;
    }

    public static void main(String[] args) {
        AppTaxIncomeHtmlParser appTaxIncomeHtmlParser = new AppTaxIncomeHtmlParser();
        String json = appTaxIncomeHtmlParser.parseAppTaxIncomeHtmlToJson("", "D:\\data\\file\\app-tax-income\\zd4pkdq81790994584563965952_0a07bc40ab96fa8d4acd34e7077738c0_tax_income2.html").getData();
        System.out.println(json);

        json = appTaxIncomeHtmlParser.parseAppTaxIncomeHtmlToJson("", "D:\\data\\file\\app-tax-income\\（无纳税）个人收入纳税明细.html").getData();
        System.out.println(json);

//        json = appTaxIncomeHtmlParser.parseAppTaxIncomeHtmlToJson("", "D:\\data\\file\\app-tax-income\\zd4t8pen1602606002052739072_ce754897fe8d796c55647d0be154c8c5_tax_income1.html").getData();
//        System.out.println(json);
//
//        json = appTaxIncomeHtmlParser.parseAppTaxIncomeHtmlToJson("", "D:\\data\\file\\app-tax-income\\zd4t8pen1602606002052739072_563079728e65403c8d3923a3eada3bb4_tax_income2.html").getData();
//        System.out.println(json);
//
//        json = appTaxIncomeHtmlParser.parseAppTaxIncomeHtmlToJson("", "D:\\data\\file\\app-tax-income\\zd4t8pen1602611424755085312_826a3f2a73e6d682a4a711819d838401_tax_income1.html").getData();
//        System.out.println(json);
//
//        json = appTaxIncomeHtmlParser.parseAppTaxIncomeHtmlToJson("", "D:\\data\\file\\app-tax-income\\zd4t8pen1602611424755085312_de87892e5cbb2d03425e1f3c19ea8376_tax_income2.html").getData();
//        System.out.println(json);
//
//        json = appTaxIncomeHtmlParser.parseAppTaxIncomeHtmlToJson("", "D:\\data\\file\\app-tax-income\\zd4t8pen1602633684299718656_6db276ec9d7b6e418d1df6c2a73c29de_tax_income1.html").getData();
//        System.out.println(json);
//
//        json = appTaxIncomeHtmlParser.parseAppTaxIncomeHtmlToJson("", "D:\\data\\file\\app-tax-income\\zd4t8pen1602633684299718656_14655b1d280e0954da4e93d5d9d96acc_tax_income2.html").getData();
//        System.out.println(json);
//
//        json = appTaxIncomeHtmlParser.parseAppTaxIncomeHtmlToJson("", "D:\\data\\file\\app-tax-income\\zd4t8pen1602915545278226432_3bf34fc06f2fba76d7092b5ed5c30d3d_tax_income1.html").getData();
//        System.out.println(json);
//
//        json = appTaxIncomeHtmlParser.parseAppTaxIncomeHtmlToJson("", "D:\\data\\file\\app-tax-income\\zd4t8pen1602915545278226432_da94967715fb7eea24dd4be7dcdd6346_tax_income2.html").getData();
//        System.out.println(json);
    }

}
